package main

import (
	"context"
	"fmt"
	"time"

	logger "gitee.com/xiaoshanyangcode/yanglog"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func main() {
	// 配置日志
	ctx, cancel := context.WithCancel(context.Background())
	logconf := logger.LogConf{}
	log := logger.NewLogger(ctx, logconf)
	defer log.Sync()
	defer cancel()

	// 生产gin对象
	r := Default(log)

	// 正常gin的用法
	r.GET("/ce", func(c *gin.Context) {
		// 取值
		req := "123"
		fmt.Println("request:", req)
		// 页面接收
		c.JSON(200, gin.H{"request": req})
	})

	r.Run()
}

// 提供gin的Default函数，把日志改为我们自定义的
func Default(log *zap.SugaredLogger) *gin.Engine {
	engine := gin.New()
	// 使用自己的日志模块和默认的recovery
	engine.Use(LoggerWithConfig(log), gin.Recovery())
	return engine
}

// 自定义日志函数
func LoggerWithConfig(log *zap.SugaredLogger) gin.HandlerFunc {
	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// Process request
		c.Next()

		param := gin.LogFormatterParams{
			Request: c.Request,
			Keys:    c.Keys,
		}

		// Stop timer
		param.TimeStamp = time.Now()
		param.Latency = param.TimeStamp.Sub(start)

		param.ClientIP = c.ClientIP()
		param.Method = c.Request.Method
		param.StatusCode = c.Writer.Status()
		param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()

		param.BodySize = c.Writer.Size()
		if raw != "" {
			path = path + "?" + raw
		}

		param.Path = path
		// 根据不同的状态码，设置不同的日志等级
		if param.StatusCode < 400 {
			log.Infow(param.ErrorMessage, "code", param.StatusCode, "client", param.ClientIP, "method", param.Method, "path", param.Path, "size", param.BodySize, "duration", param.Latency)
		} else {
			log.Errorw(param.ErrorMessage, "code", param.StatusCode, "client", param.ClientIP, "method", param.Method, "path", param.Path, "size", param.BodySize, "duration", param.Latency)
		}
	}
}
